package jsp.servlet;

import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.entities.Employee;
import jpa.entities.Project;
import jpa.entities.Task;
import jsp.classes.Session;

/**
 * @author Remco Haszing
 * @author Aymeric Blok
 */
public class NewTask extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Session session = (Session) request.getSession().getAttribute("user");
            String taskname = null;
            GregorianCalendar deadline = null;
            Project project = null;
            Employee employee = null;
            int importance = -1;
            String details = null;
            String notes = null;

            for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                String k = entry.getKey();
                String[] v = entry.getValue();
                if (k.equals("taskname")) {
                    taskname = v[0];
                } else if (k.equals("deadline")) {
                    String[] d = v[0].split("-");
                    deadline = new GregorianCalendar(Integer.parseInt(d[0]), Integer.parseInt(d[1]) - 1, Integer.parseInt(d[2]));
                } else if (k.equals("project")) {
                    project = session.findProjectById(Integer.parseInt(v[0]));
                } else if (k.equals("employee")) {
                    employee = session.findEmployeeById(Integer.parseInt(v[0]));
                } else if (k.equals("importance")) {
                    importance = Integer.parseInt(v[0]);
                } else if (k.equals("details")) {
                    details = v[0];
                } else if (k.equals("notes")) {
                    notes = v[0];
                }
            }

            System.out.println(taskname + "\n\n\n\n\n\n\n\n\n\n\n\n\n");
            Task tsk = new Task(taskname, deadline, project, employee, importance, details, notes);

            session.getJPAConnection().create(tsk);
            response.getWriter().print("true");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("false");
        }
    }
}
